<template>
  <el-dialog
    title="删除网站"
    :visible.sync="dialogVisible"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-alert type="warning" :closable="false" style="margin-bottom: 20px;">
      <strong>⚠️ 警告：此操作将删除网站及所有相关数据，且无法恢复！</strong>
    </el-alert>

    <el-form label-width="130px">
      <el-form-item label="网站名称">
        <span style="font-weight: 500;">{{ websiteName }}</span>
      </el-form-item>

      <el-form-item label="域名">
        <span style="color: #606266;">{{ websiteDomain }}</span>
      </el-form-item>

      <el-form-item label="云端图片">
        <div v-loading="loadingStats">
          <div v-if="stats.total_count > 0">
            <span style="font-weight: 500;">{{ stats.total_count }} 个图片</span>
            <span style="color: #909399; margin-left: 10px;">({{ stats.total_size_mb }} MB)</span>
          </div>
          <div v-else style="color: #909399;">
            无云端图片
          </div>
        </div>
      </el-form-item>

      <el-form-item v-if="stats.total_count > 0" label="删除云端图片">
        <el-switch
          v-model="deleteCloudImages"
          active-text="同时删除"
          inactive-text="仅删除记录"
          active-color="#F56C6C"
        />
        <div style="margin-top: 8px; font-size: 12px;">
          <div v-if="deleteCloudImages" style="color: #F56C6C;">
            <i class="el-icon-warning" /> 将从云存储（OSS/S3）中永久删除所有图片文件
          </div>
          <div v-else style="color: #E6A23C;">
            <i class="el-icon-info" /> 仅删除数据库记录，云端文件保留（可能产生存储费用）
          </div>
        </div>
      </el-form-item>

      <el-form-item label="确认删除">
        <el-input
          v-model="confirmText"
          :placeholder="`请输入域名「${websiteDomain}」以确认删除`"
          clearable
        />
        <div style="margin-top: 8px; font-size: 12px; color: #909399;">
          为了防止误删，请输入完整域名
        </div>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button
        type="danger"
        :disabled="!canDelete"
        :loading="deleting"
        @click="handleConfirm"
      >
        确认删除网站
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getCloudImageStats } from '@/api/static_web_cloud_image'
import { deleteWebsiteWithImages } from '@/api/static_web_cloud_image'

export default {
  name: 'DeleteWebsiteDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    websiteId: {
      type: [Number, String],
      default: null
    },
    websiteName: {
      type: String,
      default: ''
    },
    websiteDomain: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      loadingStats: false,
      stats: {
        total_count: 0,
        total_size_mb: 0
      },
      deleteCloudImages: false,
      confirmText: '',
      deleting: false
    }
  },
  computed: {
    canDelete() {
      return this.confirmText === this.websiteDomain
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.fetchStats()
        this.resetForm()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    async fetchStats() {
      if (!this.websiteId) return

      this.loadingStats = true
      try {
        const response = await getCloudImageStats({ website_id: this.websiteId })
        if (response.success) {
          this.stats = response.data
        }
      } catch (error) {
        console.error('获取云端图片统计失败:', error)
      } finally {
        this.loadingStats = false
      }
    },

    resetForm() {
      this.deleteCloudImages = false
      this.confirmText = ''
    },

    async handleConfirm() {
      if (!this.websiteId) {
        this.$message.error('网站ID不能为空')
        return
      }

      if (!this.canDelete) {
        this.$message.warning('请输入正确的域名以确认删除')
        return
      }

      this.deleting = true
      try {
        const response = await deleteWebsiteWithImages({
          website_id: this.websiteId,
          delete_cloud_images: this.deleteCloudImages,
          confirm: true
        })

        if (response.success) {
          this.$message.success(response.msg)

          // 显示详细结果
          if (response.data.cloud_images_deleted > 0) {
            this.$notify({
              title: '删除完成',
              message: `已删除 ${response.data.cloud_images_deleted} 个云端图片，释放 ${response.data.total_size_freed_mb} MB 空间`,
              type: 'success',
              duration: 5000
            })
          }

          // 显示错误信息（如果有）
          if (response.data.errors && response.data.errors.length > 0) {
            this.$notify({
              title: '部分图片删除失败',
              message: response.data.errors.slice(0, 3).join('\n'),
              type: 'warning',
              duration: 8000
            })
          }

          this.$emit('deleted', response.data)
          this.handleClose()
        } else {
          this.$message.error(response.msg)
        }
      } catch (error) {
        this.$message.error('删除失败：' + (error.message || '未知错误'))
        console.error(error)
      } finally {
        this.deleting = false
      }
    },

    handleClose() {
      this.dialogVisible = false
      this.resetForm()
    }
  }
}
</script>

<style scoped>
.el-form-item >>> .el-form-item__label {
  font-weight: 500;
}
</style>
